
make_bins <- function(x, quant_breaks = c(seq(0, 0.9, 0.1), 0.95, 0.99, 0.995, 0.999, 1)){
  out = quantile(x, quant_breaks, na.rm=T)
  out = cut(x, out, include.lowest=T, labels=F)
  out = factor(out, labels = as.character(head(quant_breaks,-1)))
  return(out)
}

get_legend_35 <- function(plot, legend_number = 1) {
  # Author: https://github.com/wilkelab/cowplot/issues/202
  # find all legend candidates
  legends <- get_plot_component(plot, "guide-box", return_all = TRUE)
  # find non-zero legends
  idx <- which(vapply(legends, \(x) !inherits(x, "zeroGrob"), TRUE))
  # return either the chosen or the first non-zero legend if it exists,
  # and otherwise the first element (which will be a zeroGrob) 
  if (length(idx) >= legend_number) {
    return(legends[[idx[legend_number]]])
  } else if (length(idx) >= 0) {
    return(legends[[idx[1]]])
  } else {
    return(legends[[1]])
  }
}

x_l = c('0-10','10-20','20-30','30-40','40-50','50-60','60-70',
        '70-80','80-90','90-95','95-99','99-99.5','99.5-99.9','99.9+')

c_l = c('D12', 'D16', 'D20', 'R12', 'R16', 'R20')

render_basic = function(data){
  ggplot(data, aes(x = nat_quant, color = variable, group = variable)) +
    geom_point(aes(y = f, shape = 'f'), position = position_dodge(width=.5), size = 3,alpha=0.75)+
    geom_point(aes(y = m, shape = 'm'), position = position_dodge(width=.5), size = 2,alpha=0.75) +
    geom_linerange(aes(ymin = f, ymax = m, xmin = nat_quant, xmax = nat_quant),position = position_dodge(width=.5),alpha=0.75) +
    theme_light() +
    theme(strip.background = element_rect(fill = 'grey90')) +
    scale_color_manual(values=c('deepskyblue', 'brown1', 'darkred','darkslateblue')) +
    geom_hline(yintercept = c(0), linetype = 'dashed', color = 'grey75') +
    theme(legend.position = 'right', axis.text.x = element_text(angle = 20, vjust = .75, hjust=0.5, size = 7), axis.text.y = element_text(size=7)) +
    theme(plot.subtitle=element_text(hjust=0.5)) +
    scale_x_discrete(expand = expansion(add=c(0.5,0.5)))
}

